var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongooess=require("mongoose");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var moreRouter=require("./routes/more");
var fable=require("formidable");
var fs=require("fs");
var zipper = require("zip-local");
var app = express();
app.listen(8085);


mongooess.connect("mongodb://127.0.0.1:27017/company");
var db=mongooess.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {

});


var CompanySchame=mongooess.Schema({

    companyName:String,
    peopleName:String,
    companyPhone:String,
    imgurl:String
});

var AdmSchame=mongooess.Schema({

    name:String,
    password:String,
    type:String
});

var Company=mongooess.model("infos",CompanySchame);
var Adm=mongooess.model("adms",AdmSchame);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'upload')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/more', moreRouter);



app.post("/toSendInfo",function (req,res) {

  var target=req.query;

  let newCompany=new Company({

      companyName:target.company,
      peopleName:target.peoplename,
      companyPhone: target.phone,
      imgurl:target.imageurl
  });

  newCompany.save(function (err) {

      if(err) {


      }else{

          res.json({status:"OK"});
      }
  });

});

// formidable


app.post("/toLogin",function (req,res) {

    let target=req.query;


    Adm.findOne({name:target.name,password:target.password},function (err,data) {


        if(err){


        }else {


            if(data!=null){

                res.cookie("userInfo",{user:data.name});
                res.json({status:"OK"});
            }else {

                res.json({status:"NO"});
            }

        }

    });
});

app.post("/addamd",function (req,res) {

    let targetName=req.query.name;
    let targetPass=req.query.pass;

    Adm.findOne({name:targetName},function (err,data) {

       if(err){


       } else {

       if(data!=null){

           res.json({status:"HAVE"});

       }else{

           var newadm=new Adm({

               name:targetName,
               password:targetPass,
               type:"xxx"
           });

           newadm.save(function (er) {

               if(er){

                   res.json({status:"ERR"})


               }else {


                   res.json({status:"OK"});

               }
           });

           //存储管理员

       }

      }

    });
});

app.get("/searcher",function (req,res) {

    console.log("ooooook");
    let target=req.query.tag;

    console.log(target);
    Company.find({'companyName': {'$regex': target, $options: '$i'}},function (err,data) {

        if(err){


        }else{

         if(data!=null){

             res.json({data:data});
         }else {

             res.json({data:[]});
         }
        }

    });
});

//获取公司信息
app.get("/getcompanyinfo",function (req,res) {

    console.log("OOOO");
    let currentPage=req.query.page;
    Company.find({}).limit(5).skip(currentPage*5).exec(function (err,data) {

        if(err){

        }else {

            res.json({data});
        }
    });

});

app.get("/getmyinfo",function (req,res) {

    let name=req.cookies.userInfo.user;
    res.json({info:name});

});
app.get("/deleteadm",function (req,res) {

    let id=req.query.id;

    Adm.remove({_id:id},function (err) {

        if(err){


        }else {

            console.log("OOOOK");
            res.json({status:"OK"});

        }

    });

});
//下载文件

app.get("/downloadzip",function (req,res) {


    zipper.sync.zip("./upload/images").compress().save("./upload/images.zip");
    res.download("./upload/images.zip");
  //  console.log("OOOOO");
});

app.post("/uploadimg",function (req,res) {

    var form = new fable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = './upload/images';
    form.keepExtensions = true;     //保留后缀
    form.maxFieldsSize = 20* 1024 * 1024;

    form.parse(req, function (err, fields, files) {

        if (err) {

            console.log(err);

        }

        let comanyName=fields.compyname;
        let peopleName=fields.name;
        let phoneNumber=fields.phone;
        console.log(files.img);
        console.log(files.img);
        console.log(files.path);
        let endtype;
        switch (files.img.type) {

            case 'image/jpeg':
                endtype = ".jpg";
                break;
            case "images/png":
                endtype = ".png";
                break;
            default:
                endtype = ".jpg";
                break;
        }
        let newpath="upload/images/"+comanyName+";"+peopleName+";"+phoneNumber+endtype;
        let currentpath="images/"+comanyName+";"+peopleName+";"+phoneNumber+endtype;
        fs.renameSync(files.img.path,newpath);
        res.json({uploadStatus:currentpath});
    });

});

app.get("/out",function (req,res) {


    res.cookie("userInfo",{user:""});
    res.json({status:"OK"});

});

app.get("/getPage",function (req,res) {


    Company.count({},function (err,count) {

       if(err){


       } else {

           res.json({status:count});

       }

    });


});

app.get("/adminfos",function (req,res) {

    Adm.find({},function (err,data) {


        if(err){

            res.json({status:"ERR"});
        }else{

            res.json({status:data});
        }
    });

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
